import { buildContents, buildSvg, useTemplate, useUpload } from "@sker/runtime"
import { DependencyContainer, HttpError, Injector, ROOT, toSuccess, useTransaction } from "@sker/core"
import { extname, join } from "path"
import { SysIcon } from "@sker/entities"

export const build = async (injector: DependencyContainer) => {
    const root = injector.resolve(ROOT)
    const svgPath = join(root, 'attachments')
    const result = await useTransaction(async m => {
        const list = await m.find(SysIcon, {})
        const svgs = await Promise.all(list.map(async item => {
            const svg = await buildSvg(`${item.pre}-${item.svg_name}`, join(svgPath, item.svg_path))
            const reg = /export default (.*?)\;/
            const result = svg.match(reg)
            if (result.length > 1) {
                const [, icon] = result;
                return svg.replace(`import * as React from "react";`, ``).replace(`export default ${icon}`, `window.${icon} = ${icon}`).replaceAll(/fill=.*?\s/g, '')
            }
            return;
        }))
        return buildContents(svgs.filter(it => !!it).join('\n'))
    })
    return toSuccess(result)
}

export const get = async () => {
    await useTemplate({ isDev: true })
}

export const post = async () => {
    const icon = await useTransaction(async m => {
        const icon = m.create(SysIcon, {})
        const url = await useUpload((info) => {
            const reg = /^[a-zA-Z\-\.]+$/;
            const ispass = reg.test(info.filename)
            if (!ispass) throw new HttpError(`文件名只能包含a-z和-`)
            const ext = extname(info.filename)
            icon.svg_name = info.filename.replace(ext, '');
            if (ext === '.svg') {
                return `svgs/${info.filename}`
            }
            throw new HttpError(`格式错误，图标只支持svg格式`)
        });
        icon.svg_path = url;
        return icon;
    })
    return toSuccess(icon);
}
